<template>
    <MyDialog ref="myDialog" title="新增用户" width="600px" :on-confirm="confirm" :on-cancel="clearData">
        <MyForm ref="myForm" :form-data="formData" :form-item-list="formItemList" :form-rules="formRules"></MyForm>
    </MyDialog>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus';
interface FormData {
    account: string;
    password: string;
    confirmPassword: string;
    name: string;
    avatar: MyComment.FormUploadValue;
    email: string;
    phone: string;
}

const emit = defineEmits<{
    (event: 'complete', value: boolean): void;
}>();

const formData: FormData = {
    account: '',
    password: '',
    confirmPassword: '',
    name: '',
    avatar: null,
    email: '',
    phone: '',
};

const formItemList: MyComment.FormItemProps<FormData>[] = [
    {
        prop: 'account',
        label: '账号',
        contentProps: { maxlength: 30, placeholder: '请输入1-30个字符' } as MyComment.FormItemContentProps['input'],
    },
    {
        prop: 'password',
        label: '密码',
        contentProps: {
            maxlength: 25,
            placeholder: '请输入8-25个字符',
            type: 'password',
            showPassword: true,
            name: 'password1',
            autocomplete: 'new-password',
        } as MyComment.FormItemContentProps['input'],
    },
    {
        prop: 'confirmPassword',
        label: '密码确认',
        contentProps: {
            maxlength: 25,
            placeholder: '请输入8-25个字符',
            type: 'text',
            showPassword: true,
            autocomplete: 'new-password',
        } as MyComment.FormItemContentProps['input'],
    },
    {
        prop: 'name',
        label: '昵称',
        contentProps: { maxlength: 25, placeholder: '请输入1-15个字符' } as MyComment.FormItemContentProps['input'],
    },
    {
        prop: 'email',
        label: '邮箱地址',
        contentProps: { maxlength: 100, placeholder: '请输入8-25个字符' } as MyComment.FormItemContentProps['input'],
    },
    {
        prop: 'phone',
        label: '手机号码',
        contentProps: { maxlength: 20, placeholder: '请输入11位手机号码' } as MyComment.FormItemContentProps['input'],
    },
    {
        prop: 'avatar',
        label: '用户头像',
        type: 'upload',
        contentExtends: { placeholder: '请上传100X100,大小不超过100k的png或jpg图片' } as MyComment.FormItemContentExtends['upload'],
    },
];

const confirmPasswordValidator = (_rule: any, value: string, callback: any) => {
    if (value && myForm.value) {
        if (value !== myForm.value.getData().password) {
            callback(new Error('两次密码输入不一致'));
        }
    }
    callback();
};

const phoneAndEmailValidator = (_rule: any, _value: string, callback: any) => {
    if (myForm.value) {
        const data = myForm.value.getData();
        if (data.email === '' && data.phone === '') {
            callback(new Error('邮箱地址和手机号码必须填写一个'));
        }
    }
    callback();
};

const formRules: MyComment.FormRules<FormData> = {
    account: { required: true, trigger: 'blur', message: '请输入用户账号' },
    password: [
        { required: true, trigger: 'blur', message: '请输入用户密码' },
        { min: 8, trigger: 'blur', message: '用户密码不能小于8个字符' },
    ],
    confirmPassword: [
        { required: true, trigger: 'blur', message: '请确认用户密码' },
        { validator: confirmPasswordValidator, trigger: 'blur', message: '两次密码输入不一致' },
    ],
    name: { required: true, trigger: 'blur', message: '请输入用户昵称' },
    email: { validator: phoneAndEmailValidator, trigger: 'blur', message: '邮箱地址和手机号码必须填写一个' },
    phone: { validator: phoneAndEmailValidator, trigger: 'blur', message: '邮箱地址和手机号码必须填写一个' },
    avatar: [{ trigger: 'change', type: 'file', fileSize: 1024 * 100, fileAccept: ['.png', '.jpg'], dimension: 100 }],
};

const myDialog = ref<MyComment.DialogInstance>();
const myForm = ref<MyComment.FormInstance<FormData>>();

const confirm = async (): Promise<boolean> => {
    let result = (await myForm.value?.validate()) || false;
    if (result) {
        const data = myForm.value?.getData();
        if (data) {
            const submitData = {
                account: data.account,
                password: data.password,
                name: data.name,
                nickname: data.name,
                avatar: '',
                email: data.email,
                phone: data.phone,
            };
            if (data?.avatar) {
                submitData.avatar = await MyModule.utile.imageFileToBase64(data.avatar);
            }
            const res = await MyService.account.createUser(submitData);
            if (res.code === 200) {
                emit('complete', true);
                return true;
            } else {
                ElMessage.error({
                    message: res.msg || '新增用户失败',
                });
                emit('complete', false);
                return false;
            }
        } else {
            emit('complete', false);
            return false;
        }
    }
    return result;
};

const open = () => {
    myDialog.value?.open();
    // myForm.value?.clearValidate();
};

const clearData = () => {
    // myForm.value?.clearData();
};

defineExpose({
    open,
});
</script>

<style scoped></style>
